<?php

/**
 * This is the model class for table "{{transfer}}".
 *
 * The followings are the available columns in table '{{transfer}}':
 * @property string $id
 * @property string $start_unique_id
 * @property string $transfer_unique_id
 * @property string $next_unique_id
 * @property integer $category
 * @property string $status
 * @property integer $t_index
 * @property integer $deal
 * @property integer $from_department_id
 * @property string $from_department_name
 * @property integer $to_department_id
 * @property string $to_department_name
 * @property string $handoff
 * @property string $reject_unique_id
 * @property integer $dateline
 * @property integer $create_time
 * @property integer $effective_time
 */
class Transfer extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Transfer the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{transfer}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			//array('start_unique_id, transfer_unique_id,  from_department_id,  to_department_id,  note', 'required'),
			array('category, t_index, deal, from_department_id, to_department_id, dateline, create_time, effective_time', 'numerical', 'integerOnly'=>true),
			array('start_unique_id, next_unique_id, reject_unique_id', 'length', 'max'=>32),
			array('status', 'length', 'max'=>4),
			array('from_department_name, to_department_name', 'length', 'max'=>128),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, start_unique_id, start_c_username, start_username, next_unique_id, next_username, next_c_username,transfer_usernames,transfer_unique_ids,transfer_c_usernames, category, t_index, status, deal, from_department_id, from_department_name, to_department_id, to_department_name, note, reject_unique_id, audited_unique_ids , dateline, create_time, effective_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'process'=>array(self::HAS_MANY, 'TransferProcess', 'transfer_id' , 'order'=>'t_index ASC'),
			'user'=>array(self::HAS_MANY, 'TransferUser', 'transfer_id' , 'order'=>'id ASC'),
			'index'=>array(self::HAS_MANY, 'TransferIndex', 'transfer_id' , 'order'=>'id ASC'),
			//'process'=>array(self::HAS_MANY, 'TransferProcess', 'id', 'with'=>'transfer_id', 'order'=>'create_time DESC'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'start_unique_id' => '发起人工号',
			'start_username' => '发起人',
			'start_c_username' => '发起人',
			'transfer_unique_ids' => '调动元素工号',
			'transfer_usernames' => '调动元素',
			'transfer_c_usernames' => '调动元素',
			'next_unique_id' => '当前审核元素',
			'next_username' => '下一步',
			'next_c_username' => '当前审核人',
			'category' => '调动分类',
			'status' => '状态',
			't_index' => '流程步骤',
			'deal' => 'Deal',
			'from_department_id' => '原部门ID',
			'from_department_name' => '原部门',
			'to_department_id' => '新部门ID',
			'to_department_name' => '新部门',
			'note' => '交接状况',
			'reject_unique_id' => '驳回者工号',
			'audited_unique_ids' => '审核过的人',
			'dateline' => 'Dateline',
			'create_time' => '发起时间',
			'effective_time' => '生效时间',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('start_unique_id',$this->start_unique_id,true);
		$criteria->compare('start_c_username',$this->start_c_username,true);
		$criteria->compare('transfer_usernames',$this->transfer_usernames,true);
		$criteria->compare('transfer_unique_ids',$this->transfer_unique_ids,true);
		$criteria->compare('transfer_c_usernames',$this->transfer_c_usernames,true);
		$criteria->compare('next_unique_id',$this->next_unique_id,true);
		$criteria->compare('next_c_username',$this->next_c_username,true);
		$criteria->compare('category',$this->category);
		$criteria->compare('status',$this->status,true);
		$criteria->compare('t_index',$this->t_index);
		$criteria->compare('deal',$this->deal);
		$criteria->compare('from_department_id',$this->from_department_id);
		$criteria->compare('from_department_name',$this->from_department_name,true);
		$criteria->compare('to_department_id',$this->to_department_id);
		$criteria->compare('to_department_name',$this->to_department_name,true);
		$criteria->compare('handoff',$this->handoff,true);
		$criteria->compare('reject_unique_id',$this->reject_unique_id,true);
		$criteria->compare('audited_unique_ids',$this->audited_unique_ids,true);
		$criteria->compare('dateline',$this->dateline);
		$criteria->compare('create_time',$this->create_time);
		$criteria->compare('effective_time',$this->effective_time);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}



	public function updateIndex($data , $check , $note='', $actionUserUniqueId)
	{
		$nextArr = array();
		//获取流程
		if($check == 1)
		{
			//通过 下一步
			//echo $data['transfer']->t_index;
			$nextIndex = $data['transfer']->t_index + 1;
			$nextArr = array();

			//echo $nextIndex;
			//echo count($data['transfer']->process);
			//die;

			if($nextIndex > count($data['transfer']->process)) {
				//流程结束
				$nextArr['unique_id'] = 'V000008';  //ss
				$nextArr['t_index'] = 0;
				$nextArr['action'] = 2; //通过
				$nextArr['status'] = 2;
			} else {
				//查找下一步
				foreach ($data['transfer']->process as $key => $value)
				{
					if($nextIndex == $key + 1)
					{
						$nextArr['unique_id'] = $value->unique_id;
						$nextArr['t_index'] = $value->t_index;
						$nextArr['action'] = 2; //通过
						$nextArr['status'] = 1;
						break;
					}
				}
			}
		}
		else if($check == -1) 
		{
			// 驳回  上一步
			$nextIndex = $data['transfer']->t_index - 1;
			if($nextIndex == 0)
			{
				return false;
			}
			else 
			{
				//查找下一步
				foreach ($data['transfer']->process as $key => $value)
				{
					if($nextIndex == $key + 1)
					{
						$nextArr['unique_id'] = $value->unique_id;
						$nextArr['t_index'] = $value->t_index;
						$nextArr['action'] = 3; //驳回
						$nextArr['status'] = -1;
						break;
					}
				}
			}
		}
		//die;
		//更新主表
		$data['transfer']->next_unique_id = $nextArr['unique_id'];
		$data['transfer']->audited_unique_ids = $data['transfer']->audited_unique_ids.','.$actionUserUniqueId;
		$data['transfer']->t_index = $nextArr['t_index'];
		$hecUserModel = new HecUser;
		$nextUser = $hecUserModel->findByAttributes(array('unique_id'=>$nextArr['unique_id']));
		$data['transfer']->next_username = $nextUser->username;
		$data['transfer']->next_c_username = $nextUser->c_username;
		$data['transfer']->status = $nextArr['status'];
		//echo $nextArr['status'];
		$data['transfer']->save();
		//print_r($data['transfer']->getErrors());
		//index
		$transferIndexModel = new TransferIndex;
		$transferIndexModel->transfer_id = $data['transfer']->id;
		$transferIndexModel->action_unique_id = $actionUserUniqueId;
		$transferIndexModel->action_type = $nextArr['action'];
		$transferIndexModel->t_index = $nextIndex;
		$transferIndexModel->note = $note;
		$transferIndexModel->dateline = $_SERVER['REQUEST_TIME'];
		$transferIndexModel->save();
		//发信
		$transferHtml = '';
		if($nextArr['status'] == 2) {
			$transferHtml = $this->getTransferMail($data['transfer']->id);
		}
		TSendMail::send($actionUserUniqueId , $data , $transferHtml);
		//die;
		return true;
	}

	/**
	 * 审核页权限
	 */
	public function auditCheck($data,$uniqueId)
	{
		if(($uniqueId == $data->next_unique_id) && ($uniqueId != $data->start_unique_id))
			return true;
		return false;
	}

	/**
	 * 详情页权限
	 */
	public function detailCheck($data,$uid)
	{
		//有权限查看的 hr 管理员 发起用户 接受用户 审核用户 璇姐 IT
		if(Yii::app()->session['userGroup']['transfer']==4 || Yii::app()->session['userGroup']['transfer']==2) return true;
		if($uid == $data['transfer']->start_unique_id)
			return true;
		$arr = explode(',', $data['transfer']->transfer_unique_ids);
		if(in_array($uid, $arr))
			return true;
		$arr = explode(',', $data['transfer']->audited_unique_ids);
		if(in_array($uid, $arr))
			return true;
		return false;
	}

	public function getTransferDetails($transferId)
	{
		$data = array();
		$data['transfer'] = $this->findByPk($transferId);
		//$transferProcessModel = new TransferProcess;
		//$data['transferProcess'] = $transferProcessModel->findAllByAttributes(array('transfer_id' => $transferId));
		//整理process
		$hecUserModel = new HecUser;

		if($data['transfer']->process) {
			foreach ($data['transfer']->process as $key => $value) 
			{
				$m = $hecUserModel-> findByAttributes(array('unique_id' => $value->unique_id));
				$data['transferProcessCUsernames'][] = $m->c_username;
			}
		}
		//$transferIndexModel = new TransferIndex;
		//$data['transferIndex'] = $transferIndexModel->findAllByAttributes(array('transfer_id' => $transferId));
		//整理index
		if($data['transfer']->index) {
			$i = 0;
			foreach ($data['transfer']->index as $key => $value) 
			{
				$m = $hecUserModel-> findByAttributes(array('unique_id' => $value->action_unique_id));
				$data['transferIndex'][$i]['c_username'] = $m->c_username;
				$data['transferIndex'][$i]['action_name'] = self::getActionName($value->action_type);
				$data['transferIndex'][$i]['action_time'] = date("Y-n-d H:i" , $value->dateline);
				$data['transferIndex'][$i]['note'] = $value->note;
				$i++;
			}
		}
		//print_r($data['transferIndex']);
		//die;
		return $data;
	}

	/**
	 *左侧菜单栏 数字 
	 */
	public function getCount($type,$uid)
	{
		$conditions = array();
		switch ($type) {
			case 'inbox':
				//$conditions = array('next_unique_id'=>$uid);
				return $this->countBySql("SELECT count(*) FROM ".$this->tableName()." WHERE next_unique_id = '".$uid."' AND status>-2 ");
				break;
			case 'start':
				//$conditions = array('start_unique_id'=>$uid);
				return $this->countBySql("SELECT count(*) FROM ".$this->tableName()." WHERE start_unique_id = '".$uid."' AND status>-2 ");
				break;
			case 'my':
				return $this->countBySql("SELECT count(*) FROM ".$this->tableName()." WHERE transfer_unique_ids like '%".$uid."%' AND status=2 ");
				break;
			case 'audited':
				return $this->countBySql("SELECT count(*) FROM ".$this->tableName()." WHERE audited_unique_ids like '%".$uid."%'  ");
				break;
		}
		return $this->countByAttributes($conditions);
	}

	/**
	 * 判断此调动是否可以被取消
	 */
	public function editCheck($data,$uniqueId)
	{
		if(($uniqueId == $data->start_unique_id) && ($data->status == -1))
			return true;
		else 
			return false;
	}


	public function getStatusName($s)
	{
		$t = Tinit::statusName();
		return $t[$s];
	}

	public static function getActionName($a)
	{
		$t = Tinit::actionName();
		return $t[$a];
	}


	public function getTransferMail($id)
	{
		$data = $this->getTransferDetails($id);
		//print_r($data);
		//die;
		$html .= '<h4>Dear all，'.$data['transfer']->transfer_c_usernames.'调动申请被审核完成！</h4>';
		$html .= '<div>
        <table  cellspacing="1" style="font-size:13px; " cellpadding="1" border="1"> 
            <tr>
            	<td>
                <table style="font-size:13px;" cellpadding="1" border="1">
                	 <tr> <td>人员 </td> <td>邮箱</td> <td width="200">原部门/项目组</td><td width="200">现部门/项目组</td><td width="100">生效时间</td></tr>';
        foreach($data['transfer']->user as $v)
		{
			$html .= " <tr><td>" .$v->c_username. "</td> <td>工号：".$v->unique_id ."<br />邮箱：".$v->username."</td>";
			$html .= "<td>".$data['transfer']->from_department_name."</td>";
			$html .= "<td>".$data['transfer']->to_department_name."</td>";
			$html .= "<td>".date("Y-m-d",$data['transfer']->effective_time)."</td>";
			$html .= "</tr>";
			/*
			$html .= '<tr>
                      	<td>职级变动：</td>
                        <td colspan="2">';
	        if($v->new_attr_id || $v->new_L || $v->new_M) {
	         	$html .= '<div id="new_user_info_'.$v->id.'">
	                        	<table style="font-size:13px;" >
	                            	<tr>
	                                	<td  width="70">属性 ：</td>
	                                    <td>'.HrPositionAttribute::model()->getInfoById($v->new_attr_id,'title').'</td>
	                                </tr>
	                                <tr>
	                                	<td>L：</td>
	                                    <td>'.HrPositionLevel::model()->getInfoById($v->new_L,'name').'</td>
	                                </tr>
	                                <tr>
	                                	<td>M：</td>
	                                    <td>'.HrPositionLevel::model()->getInfoById($v->new_M,'name') .'</td>
	                                </tr>
	                            </table>
	                        </div>';
	         }
	         $html .= "</td></tr>";
        	*/
        }
        $html .= '</table>
                </td>
            </tr>';
        $html .= '</table></div>';
        return $html;
	}


}